package com.iflytek.universitymanagement.controller;

import com.iflytek.universitymanagement.domain.CourseResource;
import com.iflytek.universitymanagement.domain.Resource;
import com.iflytek.universitymanagement.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/resources")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    // 查询所有资源，包括课程名称
    @GetMapping("/all")
    public List<CourseResource> getAllResources() {
        return resourceService.getAllResourcesWithCourseName();
    }

    // 根据ID查询单个资源
    @GetMapping("/{resourceId}")
    public Resource getResourceById(@PathVariable int resourceId) {
        return resourceService.getById(resourceId);
    }

     //根据课程ID查询资源
    @GetMapping("/course/{courseId}")
    public List<Resource> getResourcesByCourseId(@PathVariable int courseId) {
        return resourceService.findResourcesByCourseId(courseId);
    }


    @PostMapping("/create")
    public ResponseEntity<String> createResource(@RequestBody Resource resource) {
        try {
            boolean result = resourceService.createResource(resource);
            if (result) {
                return ResponseEntity.ok("Resource created successfully");
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed to create resource");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error creating resource: " + e.getMessage());
        }
    }
    // 更新资源
    @PutMapping("/{resourceId}")
    public String updateResource(@PathVariable int resourceId, @RequestBody Resource resource) {
        resource.setResourceId(resourceId); // 确保传递的ID与URL中的一致
        boolean isUpdated = resourceService.updateById(resource);
        return isUpdated ? "资源更新成功" : "资源更新失败";
    }

    // 删除资源
    @DeleteMapping("/{resourceId}")
    public String deleteResource(@PathVariable int resourceId) {
        boolean isDeleted = resourceService.removeById(resourceId);
        return isDeleted ? "资源删除成功" : "资源删除失败";
    }
}
